open F,"plant-training.txt";

while(!eof(F)) {

  $header = <F>;
  $header =~ /#(\d)/;
  $class = $1;
  $count[$class]++;
  
  $img = "";
  for $row_i (1..6) {
    $row_data = <F>;
    chomp($row_data);
    $img = $img.$row_data;
  }
  @imgN = split/\s+/,$img;
  shift @imgN;
  
  for $i (0..35) {
    if ($class == 1) {
      $tot[$class][$i] += $imgN[$i];
    } else {
      $tot[$class][$i] += $imgN[$i];
    }
  }
}

for $c (0..1) {
  print "#$c: $count[$c]";
  for $i (0..35) {
    print " ";
    if ($i % 6 == 0) {
      print "\n";
    }
    #print $tot[$c][$i]."\t";
    printf "%.3f\t",$tot[$c][$i]/$count[$c];
  }
  print "\n";
}

close F;


# NAIVE BAYES PERFORMANCE

open Ftest,"plant-test.txt";

$correct = 0;
$incorrect = 0;

while(!eof(Ftest)) {

  # Read in instance
  $header = <Ftest>;
  $header =~ /#(\d)/;
  $trueclass = $1;
  $img = "";
  for $row_i (1..6) {
    $row_data = <Ftest>;
    chomp($row_data);
    $img = $img.$row_data;
  }  
  @imgN = split/\s+/,$img;
  shift @imgN;
  
  for $c (0..1) {
    # Log likelihood
    $loglikelihood[$c]=0;
    for $i (0..35) {
      $p = $tot[$c][$i]/$count[$c];
      $loglikelihood[$c] += log($imgN[$i]==1?$p:1-$p);
    }
  }
  
  if( $loglikelihood[1]>$loglikelihood[0] && $trueclass==1 ||
      $loglikelihood[1]<$loglikelihood[0] && $trueclass==0) {
    $correct++;
  } else {
    $incorrect++;
  }
}

printf "Test Performance: %f\n", $correct/($correct+$incorrect);